package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.ImageUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 反馈
 *
 * @author Android
 */
public class FeedBackActivity extends BaseActivity {
    // 任务描述
    private EditText describe = null;
    // 图片添加
    private ImageView imageview = null;
    //提交
    private TextView submit = null;
    //标题
    private TextView title = null;
    private File f;
    //图片保存路径
    private File downloadUrl = new File(Environment.getExternalStorageDirectory() + "/temp");
    //图片名称
    private String imageFileName = DateUtils.getNumberDate() + ".jpg";
    Bitmap zoomBitmap;
    //加载框
    AlertDialog dialog = null;
    //数据库
    private DBManager db=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        // 加载布局
        setContentView(R.layout.feedback_activity);
        // 初始化组件
        initialization();
    }

    /**
     * 初始化
     */
    private void initialization() {
        db=new DBManager(this);
        // TODO Auto-generated method stub
        // 初始化组件
        describe = (EditText) findViewById(R.id.describe);
        imageview = (ImageView) findViewById(R.id.imageview);
        submit = (TextView) findViewById(R.id.submit);
        title = (TextView) findViewById(R.id.title_name);
        // 设置标题
        title.setText("建议反馈");
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //图片选择
        imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);
            }
        });
        //上传内容
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String data=describe.getText().toString();
                    if (NetworkUtil.isNetworkAvailable(FeedBackActivity.this)) {
                        if(data.length()>=5&&data.length()<=300){
                            dialog = new MyAlertDialog().ShowDialog(FeedBackActivity.this, R.layout.dialog_loading);
                            dialog.setCancelable(true);
                            setImgData(1,data);
                        }else{
                            ToastUtil.showToast(FeedBackActivity.this,"您输入的字数不符合规定，请确认后重新提交");
                        }
                    } else {
                        ToastUtil.showToast(FeedBackActivity.this, R.string.no_network_hint);
                    }
            }
        });
    }

    /**
     * 相册返回的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        try {
            switch (requestCode) {
                //相册
                case 1:
                    f = ImageUtils.getPhotoFromResult(this, data);
                    break;
            }

            Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
            // 缩放图片
            zoomBitmap = ImageCompressL(bitmap);
            imageview.setImageBitmap(zoomBitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setImgData(final int requestCode, final String data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (requestCode == 1) {
                        if (f != null) {
                            //保存图片
                            if (!downloadUrl.exists()) {
                                downloadUrl.mkdir();
                            }
                            f = new File(downloadUrl, imageFileName);
                            FileOutputStream out = null;
                            try {
                                out = new FileOutputStream(f);
                                if (zoomBitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                                    out.flush();
                                    out.close();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    HashMap<String, Object> param = new HashMap<>();
                    param.put("content", data);
                    param.put("adviceUrl",null);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.setFeedBack).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 200 || code == 204) {
                        loginHandler.sendEmptyMessage(1);
                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                    //上传图片
//                    String str = UploadUtil.uploadFile(f, APIMethod.CaneraActivity, db.select("access_token"));
//                    if (str.equals("200")) {

//                    } else {
//                        loginHandler.sendEmptyMessage(4);
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loginHandler.sendEmptyMessage(2);
                }
            }
        }).start();
    }

    /**
     * 图片压缩
     *
     * @param bitmap
     * @return
     */
    private Bitmap ImageCompressL(Bitmap bitmap) {
        // 获取Android屏幕的服务
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        //图片允许最大空间   屏幕宽度像素
        double maxSize = wm.getDefaultDisplay().getWidth();
        //将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        //将字节换成KB
        double mid = b.length / 1024;
        //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            //获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bitmap = zoomImage(bitmap, bitmap.getWidth() / Math.sqrt(i),
                    bitmap.getHeight() / Math.sqrt(i));
        }
        return bitmap;
    }

    /***
     * 图片的缩放方法
     *
     * @param bgimage   ：源图片资源
     * @param newWidth  ：缩放后宽度
     * @param newHeight ：缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 1:
                    try {
                        ZhugeSDK.getInstance().track(getApplicationContext(), "投诉建议");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ToastUtil.showToast(FeedBackActivity.this, "反馈成功，感谢您的建议");
                    finish();
                    break;
                case 2:
                    ToastUtil.showToast(FeedBackActivity.this, "反馈失败，请稍后重试");
                    break;
                default:
                    break;
            }
        }
    };
}
